package com.mjf.io.input;

import org.junit.Test;

import java.io.FileReader;
import java.io.IOException;

/**
 * FileReader:字符输入流(用来操作文本文件，如果处理二进制文件可能会导致文件损坏)
 */
public class FileReaderUse {

    /**
     * 单字符读取
     */
    @Test
    public void fileRead01() {
        String inputPath = "D:\\coding\\idea\\java-stu\\src\\main\\java\\com\\mjf\\io_input\\FileInputStreamUse.java";
        FileReader fileReader = null;
        int data;

        try {
            fileReader = new FileReader(inputPath);
            while((data = fileReader.read()) != -1) {
                System.out.print((char)data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 多字符读取
     */
    @Test
    public void fileRead02() {
        String inputPath = "D:\\coding\\idea\\java-stu\\src\\main\\java\\com\\mjf\\io_input\\FileInputStreamUse.java";
        FileReader fileReader = null;
        int readLen;
        char[] buf = new char[1024];    // 存放读取到的字符

        try {
            fileReader = new FileReader(inputPath);
            while((readLen = fileReader.read(buf)) != -1) {
                System.out.print(new String(buf, 0, readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fileReader != null) {
                    fileReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
